# sql_copy.pm
# Copyright (C) 2006, 2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information visit http://carrierclass.net
#
use strict; use warnings;

package CCN::sql_copy;

use CCN::Scripting;
use CCN::Scripting::sql;
use CCN::Database;

sub local_sqlite3($)
{
    my $sqlite_file = shift;
    return new CCN::Database ("dbi:SQLite:dbname=$sqlite_file",'','')
}

sub local_mysql($)
{
    my $mysql_dbname = shift;
    return new CCN::Database ("DBI:mysql:database=${mysql_dbname}",'','');
}

# sub initialize_sqlite3
# sub initialize_mysql
# sub copy

#
# --- Tools for subclasses
#

sub __copy_table($$$$)
{
    my ($db_from,$db_to,$table,$query_from) = @_;

    my $sth_from = $db_from->sqlref_do($query_from,$env);

    my @columns = @{$sth_from->{'NAME_lc'}};

    my $query_to = qq(INSERT INTO "$table")
        .'('.join(',', map { qq("$_") } @columns ).')'
        .' VALUES '
        .'('.join(',', map { q(?) } @columns ).')'
        .';';

    my $sth_to = $db_to->{dbh}->prepare($query_to) or $db_to->dbh_die($query_to);
    $db_to->sql_begin();
    while( defined( my $row_ary = $sth_from->fetchrow_arrayref() ) )
    {
        $sth_to->execute(@{$row_ary}) or $db_to->dbh_die("Running $query_to with values ".join(',',@{$row_ary}));
    }
    $db_from->dbh_die("copy_table($table,$query_from) failed: ".$sth_from->errstr."\n")
        if($sth_from->err);
    $db_to->sql_commit();
}

sub __set_version($$)
{
    my ($db_to,$version) = @_;
    if(defined $version)
    {
        $db_to->sql_do('CREATE TABLE export_version (version TEXT)') or $db_to->dbh_die('CREATE TABLE export_version');
        $db_to->sql_do('INSERT INTO export_version VALUES (?)',$version) or $db_to->dbh_die('INSERT INTO export_version');
    }
    
}

1;